package com.gaofei.controller;

import cn.hutool.core.date.DateUtil;
import com.bw.springboot.starter.upload.model.Chunk;
import com.bw.springboot.starter.upload.service.FileService;
import com.bw.springboot.starter.upload.util.FileResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("file")
public class UploadController {


    @Value("${upload.path}")
    private String uploadPath;

    @Value("${upload.domain}")
    private String uploadDomain;


    @Autowired
    private FileService fileService;

    /**
     *
     * @param chunk
     * @return
     * @throws InterruptedException
     */
    @RequestMapping("postFileUpload")
    public Object postFileUpload(@ModelAttribute Chunk chunk) throws InterruptedException {
        fileService.postFileUpload(chunk);
        if (chunk.getTotalChunks().equals(chunk.getChunkNumber())) {
            TimeUnit.SECONDS.sleep(2);
            FileResult fileResult = fileService.mergeFile(chunk);
            return fileResult;
        }
        log.info("文件上传成功");
        return "success!";
    }


    //普通的文件上传
    @RequestMapping("upload")
    //////////////////////如果不写这个:前端传过来的参数名必须叫file   写这个的话,就和里面的名称对应就可以
    public String upload(@RequestParam("fileName") MultipartFile file) throws IOException {
        String newFilename =null;
        if(file!=null && file.getSize()>0){
            //QQ图片20230815162645.jpg
            String originalFilename = file.getOriginalFilename();
            //202308181449081692341348288
            String format = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
            long time = new Date().getTime();//毫秒值
            format=format.replace("-","").replace(":","").replace(" ","")+time;
            //202308181449081692341348288.jpg   得到新的文件名
            newFilename= format+originalFilename.substring(originalFilename.lastIndexOf("."));
            //将文件写入到服务器的某个位置,或者阿里云oss,七牛云oss,minio
            file.transferTo(new File(uploadPath,newFilename));
        }
        return uploadDomain+newFilename;
    }

    @RequestMapping("testLog")
    //////////////////////如果不写这个:前端传过来的参数名必须叫file   写这个的话,就和里面的名称对应就可以
    public String upload(String logs) throws IOException {

        log.info("===========:{}",logs);
        return "success!";
    }
}
